<template>
  <h2 class="f30">移动端登录</h2>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model.trim="loginForm.username"
        :rules="[{ required: true, message: '请填写用户名' }]"
        label="用户名"
        name="username"
        placeholder="用户名"
      />
      <van-field
        v-model="loginForm.password"
        :rules="[{ required: true, message: '请填写密码' }]"
        label="密码"
        name="password"
        placeholder="密码"
        type="password"
      />
      <van-field
        v-if="captchaEnabled"
        v-model="loginForm.code"
        :rules="[{ required: true, message: '请填写验证码' }]"
        label="验证码"
        placeholder="请输入验证码"
      >
        <template #button>
          <van-image
            :src="codeUrl"
            height="36"
            width="100"
            @click="getCaptchaCode"
          />
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button block native-type="submit" round type="primary"
        >提交</van-button
      >
    </div>
  </van-form>
  <p>
    登录即代表同意<a
      v-for="item in agreements"
      :key="item.title"
      :href="item.url"
      target="_blank"
      >《{{ item.title }}》</a
    >
  </p>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { getCodeImg, getInfo, login } from "@/server/center/login.js";
import { useUsersStore } from "@/stores/user.js";
import { setToken } from "@/utils/auth.js";

const router = useRouter();
const captchaEnabled = ref(true);
const codeUrl = ref("");
const loginForm = reactive({
  username: ref(),
  password: ref(),
  code: ref(),
  uuid: ref(),
});
// 政策协议
const agreements = [
  { title: "隐私协议", url: "https://ruoyi.vip/protocol.html" },
  { title: "用户协议", url: "https://ruoyi.vip/protocol.html" },
];
// 登录按钮
const onSubmit = async (values) => {
  login(loginForm)
    .then(async (res) => {
      setToken(res.data.access_token);
      let userInfo = await getInfo();
      useUsersStore().setUserInfo(userInfo);
      await router.replace({
        path: router.currentRoute.value.query.from || "/",
      });
    })
    .catch(() => {
      getCaptchaCode();
    });
};

// 获取图形验证码
const getCaptchaCode = () => {
  getCodeImg().then((res) => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.uuid = res.uuid;
    }
  });
};
// 挂载后运行
onMounted(() => getCaptchaCode());
</script>
